export function createStorage(prefix: string, storage: 'local' | 'session' = 'local') {
  const storeageUsed = storage === 'local' ? localStorage : sessionStorage;

  class Storage {
    constructor(private prefix: string) {}

    private computedKey(key: string) {
      return `${prefix}${key}`;
    }

    /**
     * 设置值
     * @param key 键
     * @param value 值
     * @param expiresSeconds 过期时间
     */
    set(key: string, value: string, expiresSeconds: Nullable<number> = null) {
      storeageUsed.setItem(
        this.computedKey(key),
        JSON.stringify({
          value,
          expiresSeconds: expiresSeconds !== null ? Date.now() + expiresSeconds * 1000 : null,
        }),
      );
    }

    /**
     * 获取值
     * @param key 键
     * @returns 返回值
     */
    get<T>(key: string): Nullable<T> {
      const valueString = storeageUsed.getItem(this.computedKey(key));
      if (!valueString) {
        return null;
      }
      try {
        const data = JSON.parse(valueString);
        const { value, expiresSeconds } = data;
        if (expiresSeconds === null || expiresSeconds >= Date.now()) {
          return value;
        }
        this.remove(key);
      } catch {

      }
      return null;
    }

    /**
     * 删除值
     * @param key 键
     */
    remove(key: string) {
      storeageUsed.removeItem(key);
    }

    /**
     * 清空值
     */
    clear(): void {
      for (let i = 0; i < storeageUsed.length; i++) {
        const key = storeageUsed[i];
        if (key === undefined) {
          continue;
        }
        if (key.startsWith(this.prefix)) {
          storeageUsed.removeItem(key);
        }
      }
    }
  }

  return new Storage(prefix);
}
